<?php
namespace jy_paiweifee;
defined('BY_JYA') or exit('error');
class team extends \plugin{
	/*
		成团(下单后，跟进订单的teamid)
	*/
	function upteam($order){
		$this->order=$order;
		foreach($order['goods'] as $goods){
			$isset=$this->check_issetgoods($goods['goodsid']);
			if($isset){
				$this->order['total']=$goods['total'];
				$this->order['goods_id']=$goods['goodsid'];
				$pass=true;
			}
		}
		if(!$pass){
			return false;
		}
		if($order['teamid'] && $order['plugin_name']=='jy_paiweifee'){
			$teamid=$order['teamid'];
		}
		$member=pdo_get('jy_commission_member',array('mid'=>$order['mid']));
		$team=$this->getcanteam($teamid,$member['team_mid']);
		if($team=='isteam'){
			return false;
		}
		if($team){
			$p_teamid=$this->getpaiwei($team);
			$myteam_id=$this->addteam($order['mid'],$p_teamid);
			$this->addteamlog($team['id'],$order['mid'],$p_teamid,$myteam_id);
			//有邀请，刚好等于上级团,只有推荐奖励（后面改了，上上级无论什么时候（只要还在这颗树上）都有排位奖励？）
			if($member['team_mid']){
				$this->uppai_tuifee($order,$member['team_mid']);
			}
			$shmid=pdo_getcolumn('jy_paiweifee_team',array('id'=>$p_teamid,'uniacid'=>$_SESSION['uniacid']),'mid');
			if($p_teamid){
				//没邀请或者邀请人不是上级团
				if(!$member['team_mid'] || $member['team_mid']!=$shmid){
					$this->uppai_fee($order,$p_teamid);
				}
				//上上级才拿排位费（没邀请或者邀请人不是上上级团）
				$pp_teamid=pdo_getcolumn('jy_paiweifee_team_log',array('myteam_id'=>$p_teamid),'p_teamid');
				$shshmid=pdo_getcolumn('jy_paiweifee_team',array('id'=>$pp_teamid,'uniacid'=>$_SESSION['uniacid']),'mid');
				if($pp_teamid && $shshmid){
					if($member['team_mid']!=$shshmid){
						$this->uppai_fee($order,$pp_teamid);
					}
				}
			}
			$this->check_upboss($team);
		}else{
			$myteam_id=$this->addteam($order['mid'],0);
		}
		return true;
	}
	function addteam($mid=0,$p_teamid=0,$bosslevel=0){
		$mid=$mid?:$_SESSION['uid'];
		$team=pdo_get('jy_paiweifee_team',array('id'=>$p_teamid,'uniacid'=>$_SESSION['uniacid']));
		$bosslevel=$bosslevel?:$team['bosslevel'];
		$myteam=pdo_get('jy_paiweifee_team',array('status'=>0,'bosslevel'=>$bosslevel,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		if($myteam['id']){
			return $myteam['id'];
		}
		$level=intval($this->setting['pai_level']);
		$num=intval($this->setting['pai_num']);
		$level=$level?:2;
		$num=$num?:3;
		$insertdata=array(
				'uniacid'=>$_SESSION['uniacid'],
				'code'=>'SN'.get_ordersn($this->tablename('team'),'code'),
				'mid'=>$mid,
				'level'=>$level,
				'bosslevel'=>$bosslevel,
				'num'=>$num,
				'goodsid'=>$this->order['goods_id'],
				'status'=>0,
				'p_teamid'=>$p_teamid,
				'createtime'=>TIMESTAMP
		);
		if($team['bossmid']){
			$insertdata['bossmid']=$team['bossmid'];
		}elseif($team['mid']){
			$insertdata['bossmid']=$team['mid'];
		}
		pdo_insert('jy_paiweifee_team',$insertdata);
		$myteam_id=pdo_insertid();
		return $myteam_id;
	}
	function addteamlog($team_id=0,$mid,$p_teamid=0,$myteam_id=0){
		$mid=$mid?:$_SESSION['uid'];
		$insertdata=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$mid,
				'p_teamid'=>$p_teamid,
				'team_id'=>$team_id,
				'orderid'=>$this->order['id'],
				'myteam_id'=>$myteam_id,
				'createtime'=>TIMESTAMP
		);
		pdo_insert('jy_paiweifee_team_log',$insertdata);
		return true;
	}
	/*
		获取team人头
	*/
	public function getteamnum($team){
		$level=intval($this->setting['pai_level']);
		$num=intval($this->setting['pai_num']);
		$level=$level?:2;
		$num=$num?:3;
		$teamnum=pow($num,$level);
		if($level>1){
			$teamnum=$teamnum+$num;
		}
		return $teamnum;
	}
	/*
		获取team
	*/
	public function checkteam($teamid){
		$ispai=pdo_getcolumn('jy_paiweifee_team',array('status'=>0,'mid'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid']),'id');
		if($ispai){
			exi('您还有排位在进行中！不能参与其他排位！','error');
		}
		$isnum=$this->get_isnum($teamid);
		$team=pdo_get('jy_paiweifee_team',array('id'=>$teamid,'uniacid'=>$_SESSION['uniacid']));
		$teamnum=$this->getteamnum($team);
		if($isnum>0 && $isnum==$teamnum){
			exi('该排位已满！','error');
		}
		return true;
	}
	/*
		升级树
	*/
	public function check_upboss($team=array()){
		$team_mid=pdo_getcolumn('jy_commission_member',array('mid'=>$team['mid']),'team_mid');
		$isnum=$this->get_isnum($team['id']);
		$teamnum=$this->getteamnum($team);
		if($isnum>0 && $isnum==$teamnum){
			pdo_update('jy_paiweifee_team',array('status'=>1),array('uniacid'=>$_SESSION['uniacid'],'id'=>$team['id']));
			$nextbosslevel=$this->get_nextbosslevel($team);
			$pteam=$this->getcanteam(0,$team_mid,$nextbosslevel,$team['mid']);
			if($pteam=='isteam'){
				return false;
			}
			$nextbosslevel=$nextbosslevel==-1?0:$nextbosslevel;
			if($pteam){
				$p_teamid=$this->getpaiwei($pteam);
				$myteam_id=$this->addteam($team['mid'],$p_teamid,$nextbosslevel);
			}else{
				$myteam_id=$this->addteam($team['mid'],'',$nextbosslevel);
			}
			if($pteam['id']){
				$this->addteamlog($pteam['id'],$team['mid'],$p_teamid,$myteam_id);
				//循环升级后，是否能升级！
				$this->check_upboss($pteam);
			}
			if($p_teamid){
				//追加当前挡位额度
				$total=$this->get_dangnum($team['mid']);
				$this->order['total']=$this->order['total']?:1;
				$price=$total*$this->order['price']/$this->order['total'];
				$this->order['price']=$price;
				//上级拿排位费
				$this->uppai_fee($this->order,$p_teamid);
				//上上级拿排位费
				$pp_teamid=pdo_getcolumn('jy_paiweifee_team_log',array('myteam_id'=>$p_teamid),'p_teamid');
				if($pp_teamid){
					$this->uppai_fee($this->order,$pp_teamid);
				}
			}
		}
		return true;
	}
	/*
		获取team
	*/
	public function getcanteam($teamid=0,$team_mid=0,$bosslevel=0,$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$oldbosslevel=$bosslevel;
		$myteam=pdo_get('jy_paiweifee_team',array('mid'=>$mid,'status'=>0,'uniacid'=>$_SESSION['uniacid']));
		if($myteam['id']){
			return 'isteam';
		}
		if($teamid){
			$team=pdo_get('jy_paiweifee_team',array('status'=>0,'id'=>$teamid,'uniacid'=>$_SESSION['uniacid']));
		}
		if(!$team && $bosslevel){
			$bosslevel=$bosslevel==-1?0:$bosslevel;
			$team=pdo_get('jy_paiweifee_team',array('bosslevel'=>$bosslevel,'status'=>0,'uniacid'=>$_SESSION['uniacid']));
		}
		if(!$team && $team_mid && !$bosslevel){
			$team=pdo_get('jy_paiweifee_team',array('status'=>0,'mid'=>$team_mid,'uniacid'=>$_SESSION['uniacid']));
		}
		if(!$team && !$bosslevel){
			$team=pdo_get('jy_paiweifee_team',array('bosslevel'=>$myteam['bosslevel'],'status'=>0,'uniacid'=>$_SESSION['uniacid']));
		}
		$log='teamid'.$team['id'].'bosslevel:'.$bosslevel.'nextbosslevel:'.$oldbosslevel."\n";
		$log.='team_mid'.$team_mid."\n";
		$log.='mid'.$mid."\n";
		//file_put_contents(ROOT_D.'/getcanteam.txt',$log."\n",FILE_APPEND);
		return $team;
	}
	/*
		获取排位
	*/
	public function getpaiwei($team){
		$level=intval($this->setting['pai_level']);
		$num=intval($this->setting['pai_num']);
		$level=$level?:2;
		$num=$num?:3;
		$p_teamid=$team['id'];
		$isnum=pdo_count('jy_paiweifee_team_log',array('p_teamid'=>$p_teamid));
		if($isnum<$num){
			return $p_teamid;
		}
		if($level>=2){
			$p_teamids=$p_teamid;
			for($i=2;$i<=$level;$i++){
				$p_teamids=pdo_getall('jy_paiweifee_team_log',array('p_teamid'=>$p_teamids),'myteam_id','myteam_id');
				if($p_teamids){
					$p_teamids=array_keys($p_teamids);
					foreach($p_teamids as $p_teamid){
						$isnum=pdo_count('jy_paiweifee_team_log',array('p_teamid'=>$p_teamid));
						if($isnum<$num){
							return $p_teamid;
						}
					}
				}else{
					return $p_teamid;
				}
			}
		}
		return false;
	}
	/*
		获取排位排列
	*/
	public function getpaiweilogs($team){
		$level=intval($this->setting['pai_level']);
		$num=intval($this->setting['pai_num']);
		$level=$level?:2;
		$num=$num?:3;
		$paiweilogs=array();
		$p_teamids=$team['id'];
		for($i=1;$i<=$level;$i++){
				$paiweilogs[$i]=array();
				$logs=pdo_getall('jy_paiweifee_team_log',array('p_teamid'=>$p_teamids),'','myteam_id');
				if($logs){
					foreach($logs as &$item){
						$item['member']=cfc('core')->member_show($item['mid']);
						$item['member']['avatar']=$item['member']['avatar']?tomedia($item['member']['avatar']):'';
						if($item['mid']==$team['mid']){
							$nickname=$item['member']['nickname'];
						}
						$item['createtime']=date('Y-m-d h:i',$item['createtime']);
					}
					$p_teamids=array_keys($logs);
				}
				if($i==1){
					$levelnum=$num;
				}else{
					$levelnum=pow($num,$level);
				}
				$lastn=$levelnum-count($logs);
				$lastlogs=array();
				for ($k=1; $k<=$lastn; $k++) {
					$lastlogs[]=array('no'=>$k);
				}
				$paiweilogs[$i]=array(
					'logs'=>$logs,
					'lastlogs'=>$lastlogs,
				);
		}
		return $paiweilogs;
	}
	/*
		直推奖励
	*/
	function uppai_tuifee($order,$mid){
		$pai_tuifee=intval($this->setting['pai_tuifee']);
		$isadd=pdo_getcolumn('jy_commission_commission',array('pluginname'=>'jy_paiweifee','mid'=>$mid,'ordermid'=>$order['mid']),'id');
		if($isadd){
			return false;
		}
		$money=$pai_tuifee*$order['price']/100;
		$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$mid,
					'ordermid'=>$order['mid'],
					'level'=>1,
					'ordersn'=>$order['ordersn'],
					'money'=>$money,
					'pluginname'=>'jy_paiweifee',
					'createtime'=>TIMESTAMP,
					'status'=>0,
		);
		pdo_insert('jy_commission_commission',$new_commission);
		return true;
	}
	/*
		排位奖励
	*/
	function uppai_fee($order,$p_teamid){
		$pteam=pdo_get('jy_paiweifee_team',array('id'=>$p_teamid,'uniacid'=>$_SESSION['uniacid']));
		if($pteam['status']){
			return false;
		}
		$mid=$pteam['mid'];
		$pai_fee=intval($this->setting['pai_fee']);
		$money=$pai_fee*$order['price']/100;
		$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$mid,
					'type'=>22,
					'ordersn'=>$order['ordersn'],
					'money'=>$money,
					'pluginname'=>'jy_paiweifee',
					'createtime'=>TIMESTAMP,
					'status'=>0,
		);
		pdo_insert('jy_commission_commission',$new_commission);
		return true;
	}
	/*
		获取当前轮次
	*/
	function getlevel($mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$bosslevel=pdo_getcolumn('jy_paiweifee_team',array('status'=>0,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'bosslevel');
		return $bosslevel;
	}
	/*
		获取
	*/
	function get_nextbosslevel($team=array()){
		$pai_jieti=$this->setting['pai_jieti'];
		$bosslevel=$team['bosslevel'];
		$yubosslevel=$bosslevel+1;
		if(!$pai_jieti || count($pai_jieti)<1){
			return $yubosslevel;
		}
		paixu($pai_jieti,'level','asc');
		$minlevel=$pai_jieti[0]['level'];
		paixu($pai_jieti,'level','desc');
		$maxlevel=$pai_jieti[0]['level'];
		foreach($pai_jieti as $k=>$pv){
			//一档
			if($bosslevel<$minlevel-1){
				$startlevel=0;
				$nextlevel=$minlevel-1;
			}
			//当前处于某档
			if($bosslevel>=$pv['level']-1){
				$startlevel=$pv['level']-1;
				if($k){
					$nextlevel=$pai_jieti[$k-1]['level']-1;
				}else{
					$ispai_maxnum=1;
					//最大轮不减去1
					$nextlevel=$this->setting['pai_maxnum'];
				}
			}
			if($nextlevel){
				$levelnum=$nextlevel-$startlevel;
				$isnum=pdo_count('jy_paiweifee_team',array('bosslevel between'=>array($startlevel,$nextlevel-1),'status'=>1,'mid'=>$team['mid'],'uniacid'=>$_SESSION['uniacid']),'id');
				if($ispai_maxnum && $bosslevel==$nextlevel-1 && $isnum>=$levelnum){
					$nextbosslevel=-1;
					$isnew=true;
					break;
				}
				if($bosslevel==$nextlevel-1 && $isnum>=$levelnum){
					$nextbosslevel=$nextlevel;
					$isnew=true;
					break;
				}
				if($bosslevel<$nextlevel-1 && $isnum>=$levelnum){
					$nextbosslevel=$nextlevel;
					$isnew=true;
					break;
				}
				if($bosslevel==$nextlevel-1 && $isnum<$levelnum){
					$nextbosslevel=$startlevel;
					$isnew=true;
					break;
				}
				break;
			}
		}
		if($nextbosslevel>=$this->setting['pai_maxnum']){
			$nextbosslevel=-1;
		}
		$log='teamid'.$team['id'].'bosslevel:'.$bosslevel.'nextbosslevel:'.$nextbosslevel."\n";
		$log.='level'.$pv['level']."\n";
		$log.='startlevel'.$startlevel."\n";
		$log.='nextlevel'.$nextlevel."\n";
		$log.='isnum'.$isnum."\n";
		$log.='levelnum'.$levelnum."\n";
		$log.='ispai_maxnum'.$ispai_maxnum."\n";
		//file_put_contents(ROOT_D.'/nextbosslevel.txt',$log."\n",FILE_APPEND);
		if($isnew){
			return $nextbosslevel?:-1;
		}else{
			return $bosslevel+1;
		}
	}
	/*
		获取当前团队参与人数
	*/
	function get_isnum($team_id){
			$level=intval($this->setting['pai_level']);
			$num=intval($this->setting['pai_num']);
			$level=$level?:2;
			$num=$num?:3;
			$isnum=0;
			$p_teamids=$team_id;
			for($i=1;$i<=$level;$i++){
				$logs=pdo_getall('jy_paiweifee_team_log',array('p_teamid'=>$p_teamids),'','myteam_id');
				if($logs){
					$isnum +=count($logs);
					$p_teamids=array_keys($logs);
				}
			}
			return $isnum;
	}
	/*
		获取挡位商品数量
	*/
	function get_dangnum($mid=0){
			$pai_jieti=$this->setting['pai_jieti'];
			$level=$this->getlevel($mid);
			$level=$level+1;
			paixu($pai_jieti,'level','desc');
			foreach($pai_jieti as $pv){
				if($level>=$pv['level']){
					return $pv['num'];
				}
			}
			return 1;
	}
	/*
		确定轮次商品数量
	*/
	function check_num($goods_id=0,$num=1){
		$isset=$this->check_issetgoods($goods_id);
		if($isset){
			$pai_jieti=$this->setting['pai_jieti'];
			$mid=$_SESSION['uid'];
			$member=pdo_get('jy_commission_member',array('mid'=>$_SESSION['uid']));
			if($member['agent_id']){
				$team=pdo_get('jy_paiweifee_team',array('mid'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid']));
				if(!$team['id']){
					$mid=$member['agent_id'];
				}
			}
			$level=$this->getlevel($mid);
			$level=$level+1;
			paixu($pai_jieti,'level','desc');
			foreach($pai_jieti as $pv){
				if($level>=$pv['level'] && $num<$pv['num']){
					exi('您当前处于'.$level.'轮！必须购买'.$pv['num'].'件商品，才能参与！','error');
				}
			}
		}
		return true;
	}
	/*
		确定商品是否属于设置的
	*/
	function check_issetgoods($goods_id=0){
		$goods_ids=$this->setting['goods_ids'];
		foreach($goods_ids as $gv){
			if($goods_id==$gv['id']){
				return true;
			}
		}	
		return false;
	}
}